import React, { Component } from "react";
import { Card, Button, Table, Form, Input, Modal } from 'antd';
import { PlusCircleOutlined } from "@ant-design/icons"
import { reqCategoryAdd, reqCategoryList, reqCategoryUpdate } from "../../api";
import { PAGE_SIZE } from "../../config"
const { Item } = Form;

export default class Category extends Component {
    state = {
        //分类列表
        categoryList: [],
        //是否弹出弹窗
        isModalVisible: false,
        //类型：change修改 add新增
        openModalType: "",
        //当前form表单中的input内容
        currentInputValue: "",
        //当前form表单中显示的内容的id，点击修改时带过来的
        currentInputId:""
    }
    //form的ref，用来操作form
    formRef = React.createRef();
    
    /**
     * modal框的点击了确定，提交from数据，用form获得当前form中的内容，并调取form的submit方法提交
     */
    handleOk = () => {
        this.formRef.current.submit();
    }

    /**
     * modal框点击了取消，隐藏modal框，重置form中input的内容
     */
    handleCancel = () => {
        this.setState({ isModalVisible: false, currentInputValue: "" ,currentInputId:""});
        this.formRef.current.resetFields();
    }

    /**
     * form表单提交并通过rule中定义规则后的回调，根据openModalType来判断是新增还是修改，并执行相应的请求
     * @param {分类名，分类名id（修改时才会传此参数）} value 
     */
    onFinish = async (value) => {
        let newList;
        if (this.state.openModalType === "add") {
            let addResult = await reqCategoryAdd(value.name)
            newList = [...this.state.categoryList];
            newList.unshift(addResult);
        } else {
            let {currentInputId} = this.state;
            let {name} = this.formRef.current.getFieldValue();
            let updateResult = await reqCategoryUpdate(currentInputId,name);
            newList = [...this.state.categoryList];
            newList.forEach((v)=>{
                if(v._id === currentInputId){
                    v.name = updateResult.name;
                }
            })
        }

        this.setState({ isModalVisible: false, currentInputValue: "" ,currentInputId:"",categoryList:newList});
        this.formRef.current.resetFields();
    }

    /**
     * form表单提交但并未通过rule中定义的规则
     * @param {错误原因} err 
     */
    onFinishFailed = (err) => {
        //验证错了啥也不做
    }
    
    /**
     * 打开modal框
     * @param {add新增，change修改} type 
     * @param {如果type是change，则value将需要修改的整个对象都带过来} v 
     */
    openModal = (type, v) => {
        if (type === "change") {
            //https://segmentfault.com/a/1190000019670168  这里讲了setState的延迟原理
            //直接setState时，this.form.current为空，但这样回调后，就能获取this.form.current，然后可以使用formInstance的setFieldsValue重置form中input的值
            this.setState({ openModalType: type, isModalVisible: true, currentInputId:v._id, currentInputValue: v.name },()=>{
                this.formRef.current.setFieldsValue({name:this.state.currentInputValue});
            });
        } else {
            this.setState({ openModalType: type, isModalVisible: true })
        }
    }

    /**
     * 获取分类列表
     */
    getCategoryList = async () => {
        let category = await reqCategoryList();
        this.setState({ categoryList: category.reverse() });
    }

    componentDidMount() {
        this.getCategoryList();
    }

    render() {
        let columnsConfig = [{
            title: "分类",
            dataIndex: "name",
            key: "category"
        }, {
            title: "操作",
            key: "caozuo",
            render: v => { return <Button type="link" onClick={() => this.openModal("change", v)}>修改</Button> },
            width: "25%",
            align: "center"
        }];
        return (
            <div>
                <Card extra={<Button type="primary" icon={<PlusCircleOutlined />} onClick={() => this.openModal("add")}>添加</Button>} >
                    <Table dataSource={this.state.categoryList} rowKey="_id" columns={columnsConfig} bordered pagination={{ pageSize: PAGE_SIZE, showQuickJumper: true }} />
                </Card>
                <Modal title={this.state.openModalType === "change" ? "修改分类" : "新增分类"} visible={this.state.isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel} okText="确定" cancelText="取消">
                    <Form ref={this.formRef} name="horizontal_login" onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>
                        <Item
                            label="分类名"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入分类名，不能为空',
                                },
                                {
                                    pattern: /^[\w+$\u4e00-\u9fa5]/,
                                    message: "分类名是汉字、字母、数字、下划线组成"
                                }
                            ]}
                        >
                            <Input placeholder="请输入分类名" />
                        </Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}